﻿using Microsoft.EntityFrameworkCore;
using YDT_SeckillService.Domain.Entities;
using YDT_SeckillService.Domain.Enums;
using YDT_SeckillService.Domain.Interfaces;
using YDT_SeckillService.Infrastructure.Data;

namespace YDT_SeckillService.Infrastructure.Repositorys
{
    /// <summary>
    /// 秒杀活动仓储实现 - 实现秒杀活动数据访问
    /// </summary>
    public class SeckillRepository : ISeckillRepository
    {
        private readonly SeckillServiceDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SeckillRepository(SeckillServiceDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据ID获取秒杀活动
        /// </summary>
        public async Task<Seckill?> GetByIdAsync(Guid id)
        {
            return await _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .FirstOrDefaultAsync(s => s.Id == id);
        }

        /// <summary>
        /// 根据日期获取秒杀活动
        /// </summary>
        public async Task<IEnumerable<Seckill>> GetByDateAsync(DateOnly date)
        {
            return await _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .Where(s => s.SeckillDate == date)
                .OrderBy(s => s.SeckillStartTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 获取所有秒杀活动
        /// </summary>
        public async Task<IEnumerable<Seckill>> GetAllAsync()
        {
            return await _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .OrderByDescending(s => s.SeckillDate)
                .ThenBy(s => s.SeckillStartTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 获取正在进行中的秒杀活动
        /// </summary>
        public async Task<IEnumerable<Seckill>> GetActiveSeckillsAsync()
        {
            var now = DateTime.UtcNow;
            var currentDate = DateOnly.FromDateTime(now);
            var currentTime = TimeOnly.FromDateTime(now);

            return await _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .Where(s => s.TimeStatus == SeckillTimeStatus.Enabled &&
                           s.SeckillDate == currentDate &&
                           s.SeckillStartTime <= currentTime &&
                           s.SeckillEndTime >= currentTime)
                .OrderBy(s => s.SeckillStartTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 获取即将开始的秒杀活动
        /// </summary>
        public async Task<IEnumerable<Seckill>> GetUpcomingSeckillsAsync()
        {
            var now = DateTime.UtcNow;
            var currentDate = DateOnly.FromDateTime(now);
            var currentTime = TimeOnly.FromDateTime(now);

            return await _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .Where(s => s.TimeStatus == SeckillTimeStatus.Enabled &&
                           (s.SeckillDate > currentDate ||
                            (s.SeckillDate == currentDate && s.SeckillStartTime > currentTime)))
                .OrderBy(s => s.SeckillDate)
                .ThenBy(s => s.SeckillStartTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取秒杀活动
        /// </summary>
        public async Task<(IEnumerable<Seckill> Seckills, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize)
        {
            var query = _context.Seckills
                .Include(s => s.SeckillProducts) // 包含秒杀商品
                .OrderByDescending(s => s.SeckillDate)
                .ThenBy(s => s.SeckillStartTime);

            var totalCount = await query.CountAsync();
            var seckills = await query
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();

            return (seckills, totalCount);
        }

        /// <summary>
        /// 添加秒杀活动
        /// </summary>
        public async Task AddAsync(Seckill seckill)
        {
            await _context.Seckills.AddAsync(seckill);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新秒杀活动
        /// </summary>
        public async Task UpdateAsync(Seckill seckill)
        {
            _context.Seckills.Update(seckill);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除秒杀活动
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            var seckill = await _context.Seckills.FindAsync(id);
            if (seckill != null)
            {
                _context.Seckills.Remove(seckill);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 检查秒杀活动是否存在
        /// </summary>
        public async Task<bool> ExistsAsync(Guid id)
        {
            return await _context.Seckills.AnyAsync(s => s.Id == id);
        }
    }
}
